< previous page page_533 next page >

Page 533
Creating Your Own Error Handlers
Before getting into the details of using the Err and Error objects in your Visual Basic programs, let's take a look at a basic error handler in Visual Basic. Error handlers in Visual Basic have three main parts:
· The On Error Goto statement
· The error handler code
· The exit statement
The On Error Goto statement appears at the beginning of the Sub or Function. This is the line that tells Visual Basic what to do when an error occurs, as in the following example:
On Error Goto LocalErrHandler
In the preceding code line, every time an error occurs in this Sub or Function, the program immediately jumps to the LocalErrHandler label in the routine and executes the error handler code. The error handler code can be as simple or as complex as needed to handle the error. A very simple error handler would just report the error number and error message, like this:
LocalErrHandler:
   MsgBox CStr(Err.Number) & " - " & Err.Description
In the preceding code example, as soon as the error occurs, Visual Basic reports the error number (Err.Number) and the error message (Err.Description) in a message box.
The third, and final, part of a Visual Basic error handler is the exit statement. This is the line that tells Visual Basic where to go after the error handler is done with its work. There are four different ways to exit an error handler routine:
· Use the Resume keyword to return to the location in the program that caused the error in order to re-execute the same instruction.
· Use the Resume Next keywords to resume execution at the Visual Basic code line immediately following the line that caused the error.
· Use the Resume label keywords to resume execution at a specified location within the routine that caused the error. This location could be anywhere within the routinebefore or after the line that caused the error.
· Use the Exit Sub or Exit Function keywords to immediately exit the routine in which the error occurred.
Which exit method you use depends on the type of error that occurred and the error handling strategy you employ throughout your program. Error types and error handling strategies are covered later in this chapter.
Now that you have the basics of error handling, you can write some error-handling routines.

 
< previous page page_533 next page >

If you like this book, buy it!